//
//  VidyoViewController.m
//  Weiweiyunshi
//
//  Created by 王译 on 17/2/9.
//  Copyright © 2017年 王译. All rights reserved.
//

#import "VidyoViewController.h"
#import "VidyoClientConstants.h"
#import "VidyoClientMessages.h"
#import "VidyoClient.h"
#import "NSString+Base64.h"
#import "VidyoClientSample.h"
#import <WebKit/WebKit.h>
@interface VidyoViewController ()<UIWebViewDelegate>
{
    NSString *userPortal;
    NSString *userName;
    NSString *passWord;
}
@end

@implementation VidyoViewController

@synthesize webData, soapResults, xmlParser;
@synthesize vidyoEntityID, vidyoMemberStatus, vidyoClientStatus;
@synthesize signingInAlert, isSigningIn;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    userPortal = @"http://viviuc.com";
    userName = @"10013";
    passWord = @"egoo";
    [self showVidyo];
    // Do any additional setup after loading the view.
}

-(void)showVidyo{
    entityIDResult = FALSE;
    memberStatusResult = FALSE;
    joinStatus = FALSE;
    vidyoMemberStatus = nil;
    
    VidyoClientInEventRoomLink event = {0};
    //最重要的地方.
    NSString *guestVPortal = @"http://viviuc.com";
    //NSString *guestVRoomKey = @"73KOZC5T5OnrKq6jX5lYHbEdfQM";
    NSString *guestVRoomKey = @"OYwiIFxgKtCgusSr8hUq5NZp2c";//邓宇凡的房间
    NSString *guestVName = @"WY";
    NSString *guestVRoomPin =@"wangyi";
    
    NSLog(@"%@",self.guestVRoomKey);
    
    strlcpy(event.portalUri, [guestVPortal UTF8String], sizeof(event.portalUri));
    strlcpy(event.roomKey, [self.guestVRoomKey UTF8String], sizeof(event.roomKey));
    strlcpy(event.displayName, [guestVName UTF8String], sizeof(event.displayName));
    strlcpy(event.pin, [guestVRoomPin UTF8String], sizeof(event.pin));
    
    // hide keyboard
    [self.view endEditing:TRUE];
    
    if (VidyoClientSendEvent(VIDYO_CLIENT_IN_EVENT_ROOM_LINK, &event, sizeof(VidyoClientInEventRoomLink)) == false)
    {
        [signingInAlert dismissWithClickedButtonIndex:0 animated:YES];
        
        NSString *alertMsg = [NSString stringWithFormat:@"Failed to sign in"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        
    }
    else
    {
        _isInCall = true;
        isSigningIn = TRUE;
    }
    
}


-(void)login{
    entityIDResult = FALSE;
    memberStatusResult = FALSE;
    joinStatus = FALSE;
    vidyoMemberStatus = nil;
    
    VidyoClientInEventLogIn event = {0};
    
    NSString *userVPortal = userPortal;
    NSString *userVName = userName;
    NSString *userVPass = passWord;
    
    strlcpy(event.portalUri, [userVPortal UTF8String], sizeof(event.portalUri));
    strlcpy(event.userName, [userVName UTF8String], sizeof(event.userName));
    strlcpy(event.userPass, [userVPass UTF8String], sizeof(event.userPass));
    
    // hide keyboard
    
    /* Create wait alert */
    
    
    
    // send login-event to VidyoClient
    if (VidyoClientSendEvent(VIDYO_CLIENT_IN_EVENT_LOGIN, &event, sizeof(VidyoClientInEventLogIn)) == false)
    {
        [signingInAlert dismissWithClickedButtonIndex:0 animated:YES];
        
        NSString *alertMsg = [NSString stringWithFormat:@"Failed to sign in"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        isSigningIn = TRUE;
        NSLog(@"登陆成功");
    }

}

-(void)joinMyRoom{
    vidyoEntityID = nil;
    NSString *urlString = [NSString stringWithFormat:@"%@/services/v1_1/VidyoPortalUserService", userPortal];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    
    // Get the EntityId from VidyoPortal using WS User::myAccount
    NSString *soapMessage = [NSString stringWithFormat:
                             @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                             "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ns1=\"http://portal.vidyo.com/user/v1_1\">"
                             "<env:Body>"
                             "<ns1:MyAccountRequest/>"
                             "</env:Body>"
                             "</env:Envelope>"];
    
    // NSLog(@"%@", soapMessage);
    
    NSString *msgLength = [NSString stringWithFormat:@"%lu",(unsigned long)[soapMessage length]];
    [theRequest addValue: @"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"myAccount" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    
    NSString *base64 = [[NSString stringWithFormat:@"%@:%@", userName, passWord] base64];
    NSString *auth = [NSString stringWithFormat:@"Basic %@", base64];
    [theRequest addValue: auth forHTTPHeaderField:@"Authorization"];
    
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if( theConnection )
    {
        webData = [NSMutableData data];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
    
    joinStatus = TRUE;
    NSLog(@"*********************SENT SOAP Request myAccount() ******************************");
}


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSDictionary *dictionary = message.body;
    
    // Initaite the local sign in process
    VidyoClientInEventRoomLink event = {0};
    NSString *guestVPortal = dictionary[@"vidyoPortal"];
    NSString *guestVRoomKey = dictionary[@"roomKey"];
    NSString *guestVName = dictionary[@"password"];
    
    NSString *guestVRoomPin =dictionary[@"roomKey"];
    
    strlcpy(event.portalUri, [guestVPortal UTF8String], sizeof(event.portalUri));
    strlcpy(event.roomKey, [guestVRoomKey UTF8String], sizeof(event.roomKey));
    strlcpy(event.displayName, [guestVName UTF8String], sizeof(event.displayName));
    strlcpy(event.pin, [guestVRoomPin UTF8String], sizeof(event.pin));
    
    // hide keyboard
    [self.view endEditing:TRUE];
    
    if (VidyoClientSendEvent(VIDYO_CLIENT_IN_EVENT_ROOM_LINK, &event, sizeof(VidyoClientInEventRoomLink)) == false)
    {
        [signingInAlert dismissWithClickedButtonIndex:0 animated:YES];
        
        NSString *alertMsg = [NSString stringWithFormat:@"Failed to sign in"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        
    }
    else
    {
        isSigningIn = TRUE;
    }
    
}


#pragma mark - 代理协议 -

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"DONE. Received Bytes: %lu", (unsigned long)[webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", theXML);
    
    
    
    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];
    
    
    // NSLog(@"entityID = %@", vidyoEntityID);
    /* Step2: Send the joinConference if the status is online */
    if ( joinStatus )
    {
        NSString *urlString = [NSString stringWithFormat:@"%@/services/v1_1/VidyoPortalUserService", userPortal];
        NSURL *url = [NSURL URLWithString:urlString];
        NSMutableURLRequest *theJoinRequest = [NSMutableURLRequest requestWithURL:url];
        
        // Get the EntityId from VidyoPortal using WS User::myAccount
        
        NSString *soapJoinMessage = [NSString stringWithFormat:
                                     @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                                     "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ns1=\"http://portal.vidyo.com/user/v1_1\">"
                                     "<env:Body>"
                                     "<ns1:JoinConferenceRequest>"
                                     "<ns1:conferenceID>%@</ns1:conferenceID>"
                                     "</ns1:JoinConferenceRequest>"
                                     "</env:Body>"
                                     "</env:Envelope>", vidyoEntityID];
        
        // NSLog(@"%@", soapJoinMessage);
        
        NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapJoinMessage length]];
        
        [theJoinRequest addValue: @"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [theJoinRequest addValue: @"joinConference" forHTTPHeaderField:@"SOAPAction"];
        [theJoinRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
#warning
        NSString *base64 = [[NSString stringWithFormat:@"%@:%@",userName,passWord] base64];
        NSString *auth = [NSString stringWithFormat:@"Basic %@", base64];
        [theJoinRequest addValue: auth forHTTPHeaderField:@"Authorization"];
        [theJoinRequest setHTTPMethod:@"POST"];
        [theJoinRequest setHTTPBody: [soapJoinMessage dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSURLConnection *theJoinConnection = [[NSURLConnection alloc] initWithRequest:theJoinRequest delegate:self];
        if( theJoinConnection )
        {
            webData = [NSMutableData data];
        }
        else
        {
            NSLog(@"theConnection is NULL");
        }
        
        joinStatus = FALSE;
        NSLog(@"*********************SENT SOAP Request joinConference() ******************************/n");
    }
    
}

- (NSString*) getElementFromElementName: (NSString *) elementName
{
    NSArray *split = [elementName componentsSeparatedByString:@":"];
    if (!split || ([split count] != 2))
    {
        NSLog(@"Not a valid elementName '%@'", elementName);
        return NULL;
    }
    NSString *element = [split objectAtIndex:1];
    if (!element)
    {
        NSLog(@"Element is null");
        return NULL;
    }
    return [NSString stringWithString:element];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict
{
    NSString *element = [self getElementFromElementName:elementName];
    if (!element)
    {
        return;
    }
    /* separate namespace from element name */
    if( [element isEqualToString:@"entityID"])
    {
        if(!vidyoEntityID)
        {
            vidyoEntityID = [[NSMutableString alloc] initWithCapacity:256];
        }
        entityIDResult = TRUE;
    }
    else if( [element isEqualToString:@"MemberStatus"])
    {
        if(!vidyoMemberStatus)
        {
            vidyoMemberStatus = [[NSMutableString alloc] initWithCapacity:256];
        }
        memberStatusResult = TRUE;
        
    }
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if( entityIDResult )
    {
        [vidyoEntityID appendString: string];
        entityIDResult = FALSE;
        // NSLog(@"entityID = %@", vidyoEntityID);
    }
    else if (memberStatusResult)
    {
        [vidyoMemberStatus appendString: string];
        memberStatusResult = FALSE;
        
        // NSLog(@"Endpoint is %@", vidyoMemberStatus);
        if(![vidyoMemberStatus isEqualToString:@"Online"])
        {
            joinStatus = FALSE;
            
            // Show the alert with the XML that was received
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *alertMsg = [NSString stringWithFormat:@"User NOT online. Make sure User is Logged In"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertMsg message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alert show];
            });
        }
    }
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSString *element = [self getElementFromElementName:elementName];
    if (!element)
    {
        return;
    }
    
    if( [element isEqualToString:@"MyAccountResponse"])
    {
        entityIDResult = FALSE;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
